'use strict'

const { ApiController } = require('jax')

class Controller extends ApiController {
  get Model() {
    return this.ctx.model.Activity
  }

  // 匹配查询
  get searchKey() {
    return ['isOpen']
  }

  // 模糊查询
  get likeKey() {
    return ['title', 'adminMobile']
  }

  // 查询前
  async beforeIndex() {
    const { ctx, config } = this
    const { SYSTEM_TYPE_STORE } = config.constant
    const { query } = ctx
    const { helper } = ctx

    if (this.admin.systemType != SYSTEM_TYPE_STORE) throw '非法操作'

    const filter = {
      storeId: this.admin.sourceId,
    }

    return {
      filter,
    }
  }

  // 新增前
  async beforeCreate() {
    const { ctx } = this
    const { body } = ctx.request

    const store = await ctx.model.Store.findById(this.admin.sourceId)

    if (!store) throw '门店不存在'
    if (!store.canCustom) throw '不允许自定义活动'

    body.storeId = this.admin.sourceId
  }

  // 保存前
  async beforeSave() {
    const { ctx } = this
    const { body } = ctx.request

    if (body.activityDate) {
      const storeId = this.admin.sourceId

      body.startTime = `${body.activityDate} ${body.startTime}`
      body.endTime = `${body.activityDate} ${body.endTime}`

      const { startTime, endTime } = body

      const filter = {
        storeId,
        $or: [
          // 情况1：活动的开始时间在某个已有会议的时间段内
          { startTime: { $lt: startTime }, endTime: { $gt: startTime } },
          // 情况2：活动的结束时间在某个已有会议的时间段内
          { startTime: { $lt: endTime }, endTime: { $gt: endTime } },
          // 情况3：活动完全包含某个已有会议
          { startTime: { $gte: startTime }, endTime: { $lte: endTime } },
        ],
      }

      if (body.id) {
        filter._id = { $ne: body.id }
      }

      const record = await ctx.model.Activity.findOne(filter)

      if (record) throw '时间段冲突'
    }
  }
}

module.exports = Controller
